<?php

namespace App\Http\Controllers;

use App\Dics;
use Illuminate\Http\Request;

use App\Http\Requests;
use Illuminate\Support\Facades\Redirect;
use Symfony\Bridge\PsrHttpMessage\Tests\Fixtures\Response;

class DicController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $dics = Dics::all();

        $result = $this->recursion($dics->toArray(), 1);
        
        return view('system.dic.index', compact('result'));
    }

    protected function recursion($array, $index)
    {
        $result = [];

        foreach ($array as $dic) {
            $result["text"] = $dic->key;
            $result["nodeId"] = $dic->id;
            $result["parent"] = $dic->parent_id;
            $result["Extendible"] = $dic;

            $temp = Dics::where('parent_id', $index)->get()->toarray();

            if ($temp != null && count($temp) > 0) {

                $tempArray = [];

                foreach ($temp as $child) {

                    $tempArray["text"] = $child->key;
                    $tempArray["nodeId"] = $child->id;
                    $tempArray["parent"] = $child->parent_id;
                    $tempArray["Extendible"] = $child;
                }
                $result["nodes"] = $tempArray;

                return $this->recursion($result, $dic->id);
            }
            return $result;
        }
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {

    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $this->validate($request, [
            'key' => 'required',
            'val' => 'required|max:255',
            'parent_id' => 'required',
            'remark' => 'max:255',
        ]);

        Dics::create($request->all());

        return Redirect::to(url('system/dic'));
    }

    /**
     * Display the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {

    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}
